package com.stujyh.bank.service.impl;

import com.stujyh.bank.mapper.AccountMapper;
import com.stujyh.bank.pojo.Account;
import com.stujyh.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service("acctountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    public int save(Account account) {
        return accountMapper.insert(account);
    }

    @Override
    public int delteByActno(String actno) {
        return accountMapper.deleteByAcno(actno);
    }

    @Override
    public int update(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public Account getByActno(String actno) {
        return accountMapper.selectByAcno(actno);
    }

    @Override
    public List<Account> getAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromActno, String toActno, double money) {
        Account fromAccount = accountMapper.selectByAcno(fromActno);
        if (fromAccount.getBalance() < money) {
            throw new RuntimeException("余额不足，转账失败!");
        }
        Account toAccount = accountMapper.selectByAcno(toActno);
        fromAccount.setBalance(fromAccount.getBalance()-money);
        toAccount.setBalance(toAccount.getBalance()+money);
//        if(1 == 1){
//            throw new RuntimeException("异常");
//        }
        int count = accountMapper.update(fromAccount);
        count += accountMapper.update(toAccount);
        if (count < 2){
            throw new RuntimeException("转账异常");
        }
    }
}
